package com.qf.first.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
@RequestMapping("/check")
public class CheckController{
    @RequestMapping("/checkCode")
    public void checkCode(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        int width = 100;
        int height = 25;
        //1.创建一个带缓冲区的图片对象
        BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //2.获取画笔对象
        Graphics graphics = bImage.getGraphics();
        //3.设置画笔颜色
        graphics.setColor(Color.GREEN);
        //4.填充背景颜色
        graphics.fillRect(0,0,width,height);
        //5.再次设置画笔颜色
        graphics.setColor(Color.RED);
        //6.设置字体样式
        graphics.setFont(new Font("宋体",Font.BOLD,16));
        //7.生产随机数
        Random ra = new Random();
        StringBuffer st = new StringBuffer();
        int code;
        for (int i = 0; i <4 ; i++) {
            code=ra.nextInt(10);
            st.append(code+"");
            //8.写入数字
            graphics.drawString(code+"",20+i*20,ra.nextInt(5)+17);
        }
        //把验证码放到回话作用域
        HttpSession session = request.getSession();
        session.setAttribute("serveCode",st.toString());
        //9.重置画笔颜色
        graphics.setColor(Color.YELLOW);
        //10.绘制干扰线
        for (int i = 0; i <8 ; i++) {
            graphics.drawLine(ra.nextInt(width),ra.nextInt(height),ra.nextInt(width),ra.nextInt(height));
        }
        ImageIO.write(bImage,"jpg",response.getOutputStream());
    }
}
